package com.codecash.controller;

import com.codecash.controller.response.Result;
import com.codecash.entity.PageBean;
import com.codecash.entity.Task;
import com.codecash.entity.TaskOrder;
import com.codecash.service.TaskService;
import com.codecash.util.ThreadLocalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/task")
public class TaskController {
    private static final Logger logger = LoggerFactory.getLogger(TaskController.class);

    @Autowired
    private TaskService taskService;

    //发布任务
    @PostMapping("/create")
    public Result create(@RequestBody @Validated Task task) {
        // 检查帖子类型是否为 "原型设计", "前端开发" 或 "后端开发" 或"整套系统开发"
        if (!("原型设计".equals(task.getTaskType()) || "前端开发".equals(task.getTaskType()) || "后端开发".equals(task.getTaskType()) || "整套系统开发".equals(task.getTaskType()))) {
            return Result.error("任务类型只能为原型设计,前端开发,后端开发或整套系统开发");
        }
        taskService.create(task);
        return Result.success();

    }

    //查询任务
    @GetMapping("/detail/{id}")
    public Result getPostDetail(@PathVariable Long id) {
        Task task = taskService.getTaskById(id);
        if (task == null) {
            return Result.error("帖子不存在");
        }
        return Result.success(task);
    }

    //修改任务
    @PostMapping("/update")
    public Result update(@RequestBody @Validated Task task) {
        // 先校验任务ID是否为空
        if (task.getId() == null) {
            return Result.error("任务ID不能为空");
        }

        try {
            taskService.update(task);
            return Result.success("任务更新成功");
        } catch (Exception e) {
            return Result.error(e.getMessage()); // 捕获帖子不存在等其他异常
        }
    }

    //删除任务
    @DeleteMapping("/delete")
    public Result delete(Task task) {
        if (task.getId() == null) {
            return Result.error("任务ID不能为空");
        }
        try {
            taskService.delete(task);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }

    // 条件分页查询任务列表
    @GetMapping("/list")
    public Result<PageBean<Task>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer TaskId

    ){
    PageBean<Task> pb = taskService.list(pageNum,pageSize,TaskId);
    return Result.success(pb);

    }
    // 查询我所有帖子

    @GetMapping("/allmytasks")
    public Result<List<Task>> getAllmyTask(){
        // 从 ThreadLocal 获取当前用户的 ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Long currentUserId = ((Number) map.get("id")).longValue();
        List<Task> tasks = taskService.findAllmyTasks(currentUserId);
        return Result.success(tasks);

    }

    @PostMapping("/order")
    public Result order(@RequestBody Map<String, Long> params) {
        logger.info("Receiving order request with params: {}", params);
        Long taskId = params.get("taskId");
        
        // 从ThreadLocal获取当前用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        
        logger.info("User {} attempting to order task {}", userId, taskId);
        
        try {
            taskService.orderTask(taskId, userId);
            return Result.success("接单成功");
        } catch (Exception e) {
            logger.error("Order task failed", e);
            return Result.error(e.getMessage());
        }
    }
    //接单
    @GetMapping("/orders")
    public Result<List<TaskOrder>> getUserOrders() {
        logger.info("Getting user orders");
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        logger.info("User ID: {}", userId);
        
        try {
            List<TaskOrder> orders = taskService.getUserOrders(userId);
            logger.info("Found {} orders", orders.size());
            return Result.success(orders);
        } catch (Exception e) {
            logger.error("Error getting user orders", e);
            return Result.error("获取订单列表失败");
        }
    }
    //接单状态
    @PostMapping("/status")
    public Result updateTaskOrderStatus(@RequestBody Map<String, Object> params) {
        logger.info("Received params: {}", params);

        // 参数校验
        if (params.get("taskId") == null) {
            logger.error("taskId is null");
            return Result.error("任务ID不能为空");
        }
        if (params.get("status") == null) {
            logger.error("status is null");
            return Result.error("状态不能为空");
        }

        String status = params.get("status").toString();
        // 验证状态值
        if (!TaskOrder.STATUS_IN_PROGRESS.equals(status) && 
            !TaskOrder.STATUS_COMPLETED.equals(status) && 
            !TaskOrder.STATUS_CANCELLED.equals(status)) {  // 添加取消状态验证
            logger.error("Invalid status value: {}", status);
            return Result.error("无效的状态值，只能是'进行中'、'已完成'或'已取消'");
        }

        try {
            Long taskId = Long.parseLong(params.get("taskId").toString());
            
            Map<String, Object> map = ThreadLocalUtil.get();
            Long userId = ((Number) map.get("id")).longValue();
            
            logger.info("Updating task order status: taskId={}, status={}, userId={}", 
                       taskId, status, userId);
            
            taskService.updateOrderStatusByTaskId(taskId, userId, status);
            return Result.success("订单状态更新成功");
        } catch (NumberFormatException e) {
            logger.error("Invalid taskId format", e);
            return Result.error("无效的任务ID格式");
        } catch (Exception e) {
            logger.error("Failed to update task order status", e);
            return Result.error(e.getMessage());
        }
    }
}